<?php

namespace App\Console\Commands;

use App\Admin\Models\SiteCompany;
use App\Store\Models\Goods\GoodsStockin;
use App\Store\Models\Goods\GoodsStockinInfolist;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class Training extends Command
{
    /**
     * The name and signature of the console command.
     * 每天凌晨跑一次
     * @var string
     */
    protected $signature = 'command:Training';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '刷培训账号数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Log::info('刷培训账号数据开始');
        $this->training();
        Log::info('刷培训账号数据结束');
        return 0;
    }

    public function training()
    {
        $ymd = date('Y-m-d', (time()-86400));
        $start_time = strtotime($ymd . ' 00:00:00');
        $end_time   = strtotime($ymd . ' 23:59:59');

        $company_list = $this->getcompanylist();
        if ($company_list != 0) {
            foreach ($company_list as $company) {
                $this->stockin($company, $start_time, $end_time);
            }
        }
    }

    /**
     * 公司列表
     */
    public function getcompanylist()
    {
        $company_list = SiteCompany::where('training_min', '>', 0)->orWhere('training_max', '>', 0)->get();
        if (!$company_list) {
            Log::info('培训公司列表为空');
            return 0;
        }
        return $company_list->toArray();
    }

    /**
     * 入库明细
     */
    public function stockin($company, $start_time, $end_time)
    {
        $stockin_list = GoodsStockin::where(['cp_id' => $company['id']])
            ->where('paymoney', '>', $company['training_min'])
            ->where('paymoney', '<', $company['training_max'])
            ->where('create_at', '>=', $start_time)
            ->where('create_at', '>=', $end_time)
            ->get()->toArray();
        if (!$stockin_list) {
            Log::info('公司id'.$company['id'].'入库明细列表为空');
            return 0;
        }

        $stockin_id = [];
        foreach ($stockin_list as $stockin) {
            $stockin_id[] = $stockin['id'];
        }

        $stockin_id_chunk = array_chunk($stockin_id, 100);

        foreach ($stockin_id_chunk as $chunk) {
            GoodsStockinInfolist::whereIn('p_id', $chunk)->update(['is_training' => 2]);
        }
        return 0;
    }
}
